import 'dart:async';
import 'package:app/constants/http_constants.dart';
import 'package:app/http/api_service.dart';
import 'package:app/router/router.dart';
import 'package:app/store/index.dart';
import 'package:app/widgets/message.dart';
import 'package:creato_ui/form/form_style.dart';
import 'package:flutter/material.dart';
import 'package:creato_ui/creato_ui.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginState();
}

class _LoginState extends State<LoginPage> {
  final accountNotifier = ValueNotifier<String?>(null);
  final codeFocusNode = FocusNode();
  Map<String, dynamic> data = {};

  List<FormSchema> get _schemas => [
        FormSchema(
          field: "account",
          component: EComponent.input,
          label: "+86",
          value: "17681882872",
          onFormItemChange: (value) {
            accountNotifier.value = value;
          },
        ),
        FormSchema(
            field: "code",
            component: EComponent.input,
            focusNode: codeFocusNode,
            suffix: ValueListenableBuilder<String?>(
              valueListenable: accountNotifier,
              builder: (context, account, child) {
                return SendCode(
                  account: account,
                  onTap: () {
                    codeFocusNode.requestFocus();
                  },
                );
              },
            ))
      ];

  // 登录
  _handleLogin(Map<String, dynamic> data) async {
    if (data['account'] == null) {
      return Message.showToast(msg: "请输入手机号");
    }
    if (data['code'] == null) {
      return Message.showToast(msg: "请输入验证码");
    }
    // CreatoUIMessage.showToast(context, msg: "登录成功");
    ApiService(context).login(data['account'], data['code']).then(
      (value) {
        if (value.code == HttpConstants.SUCCEED_CODE) {
          Message.showToast(msg: "登录成功");
          UserModel user = Provider.of<UserModel>(context, listen: false);
          user.token = value.data;
          ApiService(context).getUserInfo().then((value) {
            if (value.code == HttpConstants.SUCCEED_CODE) {
              UserModel userModel =
                  Provider.of<UserModel>(context, listen: false);
              userModel.userInfo = value.data;
              router.replace("/home");
            }
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: [
            const Expanded(
                child: DecoratedBox(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xFFDFEFFF),
                      Colors.white,
                    ]),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    FlutterLogo(
                      size: 100,
                    ),
                    Text(
                      "欢迎使用  项目执",
                      style: TextStyle(
                          color: Colors.black,
                          fontSize: 30,
                          fontWeight: FontWeight.bold),
                    )
                  ],
                ),
              ),
            )),
            Expanded(
                flex: 2,
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 27.5),
                  child: Column(
                    children: [
                      CreatoUIForm(
                        schemas: _schemas,
                        formStyle: const CreatoUIFormStyle(
                            itemPadding: EdgeInsets.symmetric(horizontal: 10)),
                        filled: true,
                        separated: false,
                        setFormFieldValue: (field, value) {
                          data[field] = value;
                        },
                      ),
                      CreatoButton(
                        text: "登录",
                        block: true,
                        onPressed: () => _handleLogin(data),
                      ),
                    ],
                  ),
                )),

            // ElevatedButton(
            //     onPressed: () async {
            //       Auth auth = await ApiService().login();
            //       UserModel user =
            //           await Provider.of<UserModel>(context, listen: false);
            //       user.token = auth.token;
            //       router.replace("/home");
            //     },
            //     child: const Text("登录"))
          ],
        ),
      ),
    );
  }
}

// 发送验证码按钮
class SendCode extends StatefulWidget {
  final String? account;
  final void Function()? onTap;
  const SendCode({super.key, this.account, this.onTap});

  @override
  State<SendCode> createState() => _SendCodeState();
}

class _SendCodeState extends State<SendCode> {
  Timer? _timer;
  bool _disabled = false; // 是否禁止点击发送验证码
  int _count = 60;
  String? get _account => widget.account;

  void _startCount() {
    if (_disabled) {
      return;
    }
    if (_account == null) {
      Message.showToast(msg: "请输入手机号");
      return;
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(_account!)) {
      Message.showToast(msg: "请输入正确的手机号");
      return;
    }
    if (widget.onTap != null) {
      widget.onTap!();
    }
    setState(() {
      _disabled = true;
    });

    ApiService(context).getCaptcha(_account!).then(
      (value) {
        if (value.code == HttpConstants.SUCCEED_CODE) {
          Message.showToast(msg: "验证码已发送,请注意查收!");
        }
      },
    );

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _count--;
      });
      if (_count == 0) {
        _disabled = false;
        _count = 60;
        _timer?.cancel();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return FractionallySizedBox(
        heightFactor: 1,
        child: GestureDetector(
            onTap: () {
              _startCount();
            },
            child: Container(
              height: double.infinity,
              constraints: BoxConstraints(minWidth: 80),
              alignment: Alignment.center,
              child: Text(
                _disabled ? "${_count}s可重发" : "发送验证码",
                style: const TextStyle(
                  color: Colors.blue,
                ),
              ),
            )));
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}
